<template>
  <div class="module-detail">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'ModuleList' }">模块列表</el-breadcrumb-item>
      <el-breadcrumb-item>
        {{ editMode ? `编辑模块详情 -- ${title}` : '新增模块详情' }}
      </el-breadcrumb-item>
    </el-breadcrumb>

    <el-collapse v-model="collapse">
      <el-collapse-item title="模块元数据编辑" name="1">
        <el-form :model="info" :rules="moduleRule" ref="moduleForm">
          <el-row v-if="editMode">
            <el-col class="time-text">
              <el-col :span="4">创建时间: {{ info.createdAt }}</el-col>
              <el-col :span="4">更新时间: {{ info.updatedAt }}</el-col>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="8">
              <el-form-item prop="title" label="模块标题">
                <el-input v-model="info.title"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="subTitle" label="模块副标题">
                <el-input v-model="info.subTitle"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="code" label="模块类型">
                <module-type-sl v-model.number="info.code"></module-type-sl>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="8">
              <el-form-item prop="online" label="上下线状态">
                <online-sl v-model.number="info.online"></online-sl>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item prop="client" label="使用平台">
                <client-sl v-model.number="info.client"></client-sl>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="4">
              <el-form-item prop="changable" label="是否开启换一换">
                <change-sl v-model.number="info.changable"></change-sl>
              </el-form-item>
            </el-col> -->
          </el-row>

          <el-row :gutter="30">
            <el-col :span="8">
              <el-form-item prop="moreText" label="外链文案(不填文案,页面上不会显示)">
                <el-input v-model="info.moreText"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="moreLink" label="外链地址">
                <el-input v-model="info.moreLink"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item prop="dataType" label="数据来源">
                <data-type-sl v-model.number="info.dataType"></data-type-sl>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="apiUrl" label="接口数据的接口地址">
                <el-input v-model="info.apiUrl"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-button type="success" v-if="editMode" @click="save" :loading="saving">
              保存模块基本配置
            </el-button>
            <el-button type="primary" v-else @click="save" :loading="saving">新增模块</el-button>
          </el-row>
        </el-form>
      </el-collapse-item>
      <!-- 2 -->
      <el-collapse-item title="模块下数据编辑" name="2" v-if="info.id && info.dataType == 0">
        <div class="data-edit edit-container order-container">
          <span>模块数据列表</span>
          <span class="module-icon">
            <i
              :class="{ 'el-icon-s-operation': true, 'is-active': !isActive }"
              @click="() => (isActive = false)"
            ></i>
            <i
              :class="{ 'el-icon-menu': true, 'is-active': isActive }"
              @click="() => (isActive = true)"
            ></i>
          </span>
          <!-- 表格数据 -->
          <el-table :data="elementList" tooltip-effect="dark" v-show="!isActive" row-key="id">
            <el-table-column
              label="序列"
              type="index"
              align="center"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="图文信息名称" align="left" show-overflow-tooltip>
              <template slot-scope="scope">
                <img
                  v-if="scope.row.content.image"
                  :src="scope.row.content.image"
                  class="module-table-img"
                  alt=""
                />
                <span>
                  {{
                    scope.row.content.title ||
                      (scope.row.content.courses ? scope.row.content.courses[0].title : '') ||
                      (scope.row.content.creators ? scope.row.content.creators[0].nickname : '') ||
                      (scope.row.content.works ? scope.row.content.works[0].title : '') ||
                      (scope.row.content.categories ? scope.row.content.categories[0].title : '')
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>
                  {{ scope.row.online == 1 ? '上线' : '未上线' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="410px">
              <template slot-scope="scope">
                <el-button icon="el-icon-rank">点我拖动</el-button>
                <el-button type="primary" @click="() => (isActive = true)">
                  跳转到目标模块数据
                </el-button>
                <el-button type="danger" icon="el-icon-delete" @click="removeModule(scope.row.id)">
                  移除模块数据
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 块数据 -->
          <draggable v-model="elementList" v-show="isActive" handle=".drag-btn">
            <div
              class="element"
              v-for="(element, index) in elementList"
              :key="index"
              :class="{ offline: !element.online }"
            >
              <div class="element-body order-increment">
                <div class="element-order">
                  <el-button icon="el-icon-rank" class="drag-btn">拖我移动</el-button>
                  <el-checkbox
                    v-model="element.checked"
                    label="选中"
                    style="margin-left: 10px"
                    @change="elementChange(element.checked, index)"
                  ></el-checkbox>
                </div>
                <!-- <img :src="element.content.cover" class="element-cover" /> -->
                <!-- <div class="element-info">{{ element.content }}</div> -->
                <dynamic-form
                  :formConfig="ModuleType[info.code].formConfig"
                  v-model="element.content"
                  ref="form"
                  :rules="rules"
                ></dynamic-form>
                <el-switch
                  v-model="element.online"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="已上线"
                  :active-value="1"
                  inactive-text="未上线"
                  :inactive-value="0"
                ></el-switch>
              </div>
            </div>
          </draggable>
          <edit-bar>
            <el-checkbox
              label="全选"
              v-show="isActive"
              v-model="checkAll"
              @change="handleCheckAllChange"
            ></el-checkbox>
            <el-button
              type="danger"
              icon="el-icon-close"
              @click="del"
              v-show="isActive"
              :disabled="selectedElement.length === 0"
            >
              删除数据
            </el-button>

            <div class="selected-element-box" v-if="selectedElement.length > 0">
              <span class="item" v-for="(element, index) in selectedElement" :key="index">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="element.content.title"
                  placement="top"
                >
                  <img
                    :src="
                      `${element.content.bannerImg ||
                        element.content.cover ||
                        (element.content.creators && element.content.creators[0].avatar) ||
                        element.content.image}?x-oss-process=image/resize,m_fill,h_30,w_30`
                    "
                  />
                </el-tooltip>
              </span>
            </div>

            <template slot="right">
              <data-pool btn-text="添加数据" @select="dataPoolSelect"></data-pool>

              <el-button
                type="success"
                icon="el-icon-check"
                @click="saveElementList"
                :loading="elementSaving"
              >
                保存模块下的数据
              </el-button>
            </template>
          </edit-bar>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script>
  import EditMixins from 'mixins/Edit';
  import { FormRuleConf } from '@/config';
  import DataPool from 'comp/DataPool';
  import DynamicForm from 'comp/DynamicForm';
  import EditBar from 'comp/EditBar';
  import ModuleType from 'config/ModuleType';

  import Sortable from 'sortablejs';

  export default {
    mixins: [EditMixins],
    data() {
      return {
        collapse: ['2'],
        title: '',
        elementList: [],
        elementSaving: false,
        elementChecked: [],
        ModuleType,
        ...FormRuleConf.Module,
        rules: {},

        // 切换是否active
        isActive: true,
      };
    },
    components: {
      DataPool,
      DynamicForm,
      EditBar,
    },
    computed: {
      selectedElement() {
        return this.elementList.filter((element) => element.checked);
      },
      checkAll: {
        get() {
          return (
            this.selectedElement.length > 0 &&
            this.selectedElement.length == this.elementList.length
          );
        },
        set(val) {},
      },
    },
    watch: {
      isActive(value) {
        if (!value) {
          this.rowDrop();
        }
      },
    },
    methods: {
      // 模块全选
      elementChange(val, index) {
        this.elementList = this.elementList.map((element, i) => {
          if (index == i) element.checked = val;
          return element;
        });
      },
      handleCheckAllChange(val) {
        this.checkAll = val;
        if (val) {
          this.elementList = this.elementList.map((element) => {
            element.checked = true;
            return element;
          });
        } else {
          this.elementList = this.elementList.map((element) => {
            element.checked = false;
            return element;
          });
        }
      },
      /**
       * 获取模块信息
       */
      getInfo() {
        if (!this.id || this.infoGetting) return;

        this.infoGetting = true;
        this.$service
          .CmsModuleInfo({ id: this.id })
          .then((res) => {
            this.info = { ...res };
            this.title = res.title;
            if (this.info.code === 'JMSimpleBanner') {
              this.rules = FormRuleConf.Module.bannerRule;
            }
            return this.getElementList();
          })
          .finally(() => {
            this.infoGetting = false;
          });
      },
      /**
       * 获取模块下的数据
       */
      getElementList() {
        if (!this.id) return;
        this.elementList = [];
        this.$service.CmsElementList({ moduleId: this.id, size: 1000 }).then((res) => {
          this.elementList = [...res.rows];
        });
      },
      /**
       * 新增或者保存模块信息
       */
      save() {
        if (this.saving) return;

        this.$refs['moduleForm'].validate((valid) => {
          if (valid) {
            this.saving = true;

            this.$service
              .CmsModuleSave(this.info, JSON_HEADER)
              .then((res) => {
                this.$message.success('模块操作成功!');
                this.$tabs.open({ name: 'ModuleDetail', params: { id: res } });
              })
              .finally(() => {
                this.saving = false;
              });
          }
        });
      },
      /**
       * 删除数据
       */
      del() {
        if (this.elementSaving) return;

        this.$confirm('确认删除选择的这几个数据吗?删掉了就没有了哦').then((res) => {
          this.elementSaving = true;
          this.$service
            .CmsElementDelete({
              elementIds: this.selectedElement.map((element) => element.id).join(','),
            })
            .then((res) => {
              this.$message.success('删除成功');
              this.getElementList();
            })
            .finally(() => {
              this.elementSaving = false;
            });
        });
      },
      /**
       * 数据池中选择了数据
       * 增加到当前页面的elementList中
       */
      async dataPoolSelect(selectedData, selectedType) {
        console.log(selectedData);
        var creatorsList = new Map();
        if (
          this.info.code === 'JMBigPic' ||
          this.info.code === 'JMPictureWork' ||
          this.info.code === 'JMLRSmallPic'
        ) {
          for (var i = 0; i < selectedData.length; i++) {
            await this.$service
              .WorkpoolCreatorList({
                uuid: selectedData[i].uid,
                nickname: '',
                order: '',
                page: 1,
                size: 10,
              })
              .then((res) => {
                creatorsList.set(i, res.rows);
              });
          }
        }
        this.elementList = [
          ...(selectedData.length === 0
            ? [
                {
                  moduleId: this.id,
                  online: 0,
                  sortnum: 0,
                  content: {},
                },
              ]
            : selectedData.map((data, index) => {
                var contentData = { ...data };

                contentData.title = data.title || data.nickname;
                contentData.bannerImg = data.bannerImg || data.cover || data.avatar;
                contentData.image = data.image || data.cover || data.avatar;

                if (this.info.code === 'CollegeBanner') {
                  contentData.thumbnail = contentData.bannerImg;
                }

                if (contentData.workId) {
                  contentData.targetType = '作品';
                  contentData.id = contentData.workId;
                  contentData.jumpUrl = 'mtjimu://works?id=' + contentData.workId;
                }

                if (
                  this.info.code === 'JMYKCategory' ||
                  this.info.code === 'JMYKDoubleHorizontalImg' ||
                  this.info.code === 'JMYKCustomLearn' ||
                  this.info.code === 'JMYKOfflineTrain' ||
                  this.info.code === 'JMYKVerticalImg' ||
                  this.info.code === 'JMYKWorkTogther' ||
                  this.info.code === 'JMYKSXY'
                ) {
                  if (contentData.courseId) {
                    contentData.targetType = '合集';
                    contentData.id = contentData.courseId;
                    contentData.jumpUrl = 'mtjimu://dcourse?id=' + contentData.courseId;
                    // 方便IOS，删除courseId
                    delete contentData.courseId;
                  } else if (contentData.videoId) {
                    contentData.id = contentData.videoId;
                    contentData.targetType = '合集';
                    contentData.jumpUrl = 'mtjimu://dcourse?id=' + contentData.videoId;
                  }
                }

                if (creatorsList.size) {
                  contentData.creators = creatorsList.get(index);
                }

                if (this.info.code === 'JMPictureWork') {
                  var creator = contentData.creators;
                  let { cover, ...work } = contentData;
                  contentData = {};
                  contentData.works = [work];
                  contentData.creators = creator;
                }

                // 存有疑问先别删除
                // contentData.image = contentData.cover || '';

                if (
                  this.info.code === 'JMCreatorWorkList' ||
                  this.info.code === 'JMCreator' ||
                  this.info.code === 'JMCreatorList'
                ) {
                  var content = {};
                  content.works = contentData.works;
                  content.creators = [contentData];
                  contentData = {};
                  contentData = content;
                }

                if (
                  this.info.code === 'JMSimpleCreator' ||
                  this.info.code === 'CreatorHRecommend' ||
                  this.info.code === 'JMTalentsSkillRecommend'
                ) {
                  contentData = JSON.parse(
                    JSON.stringify(contentData, ['uuid', 'avatar', 'nickname']),
                  );
                  var creators = [contentData];
                  contentData = {};
                  contentData.creators = creators;
                }

                if (
                  this.info.code === 'JMYKLeftImgRightMessage' ||
                  this.info.code === 'JMYKDoubleHorizontalImgHavePrice'
                ) {
                  let temp = contentData.showVideoId ? contentData.showVideoId : '';

                  if (contentData.courseId || contentData.videoId) {
                    contentData = JSON.parse(
                      JSON.stringify(contentData, [
                        'cover',
                        'title',
                        'courseId',
                        'videoId',
                        'level',
                      ]),
                    );
                    if (temp) {
                      contentData.videoId = temp;
                    }
                    var courses = [contentData];
                    contentData = {};

                    contentData.courses = courses;
                  }
                }

                // 只要这些数据
                if (this.info.code === 'JMAutoPlayBanner') {
                  contentData = JSON.parse(
                    JSON.stringify(contentData, [
                      'image',
                      'title',
                      'jumpUrl',
                      'videoId',
                      'targetType',
                    ]),
                  );
                }

                if (this.info.code === 'Activity') {
                  contentData = JSON.parse(JSON.stringify(contentData, ['kind', 'title', 'actId']));
                }

                if (this.info.code === 'ActivityBigImg') {
                  contentData = JSON.parse(JSON.stringify(contentData, ['kind', 'title', 'actId', 'actEndTime']));
                }

                if (this.info.code === 'IndexBanner') {
                  contentData = JSON.parse(
                    JSON.stringify(contentData, [
                      'bannerImg',
                      'title',
                      'subTitle',
                      'bgColor',
                      'jumpUrl',
                      'targetType',
                      'targetId',
                    ]),
                  );
                }

                if (this.info.code === 'JMYKPersonImg') {
                  contentData = JSON.parse(
                    JSON.stringify(contentData, ['uuid', 'avatar', 'nickname', 'info']),
                  );
                  var creators = [contentData];
                  contentData = {};
                  contentData.creators = creators;
                }

                if (this.info.code === 'JMCategory') {
                  if (contentData.categories) {
                    contentData.categories.map((category) => {
                      category.bgImage = category.bgImgurl;
                    });
                  } else {
                    var categories = contentData;
                    contentData.bgImage = contentData.bgImgurl;
                    contentData = {};
                    contentData.categories = [categories];
                  }
                }

                // 选择学习路径
                if (contentData.learnPathId) {
                  contentData.targetType = '学习路径';
                  contentData.id = contentData.learnPathId;
                  contentData.jumpUrl = 'mtjimu://ktpath?id=' + contentData.learnPathId;
                }

                // 选择商品
                if (contentData.productId) {
                  contentData.targetType = '商品';
                  contentData.jumpUrl = 'mtjimu://product?id=' + contentData.productId;
                }

                return {
                  moduleId: this.id,
                  online: 0,
                  sortnum: 0,
                  content: contentData,
                };
              })),
        ].concat([...this.elementList]);
        console.log(this.elementList);
      },
      /**
       * 保存模块下的所有数据源数据
       */
      saveElementList() {
        this.$refs.form[0].$children[0].validate((valid) => {
          if (valid) {
            if (this.elementSaving) return;
            this.elementSaving = true;
            this.$service
              .CmsElementBatchSave(
                this.elementList.map((element, index) => {
                  element.sortnum = index;
                  if (this.info.code === 'JMBigPic') {
                    // 处理安卓显示不了的问题
                    element.content.creators &&
                      element.content.creators.forEach((item) => {
                        item.identified = !Array.isArray(item.identified) ? item.identified : 0;
                      });
                  }
                  return element;
                }),
                JSON_HEADER,
              )
              .then((res) => {
                this.$message.success('保存数据源成功!');
                // 刷新数据源列表
                this.getElementList();
              })
              .finally(() => {
                this.elementSaving = false;
              });
          }
        });
      },

      // 行拖拽
      rowDrop() {
        // 此时找到的元素是要拖拽元素的父容器
        const tbody = document.querySelector('.el-table__body-wrapper tbody');
        const _this = this;
        Sortable.create(tbody, {
          // 指定父元素下可被拖拽的子元素
          draggable: '.el-table__row',
          onEnd({ newIndex, oldIndex }) {
            const currRow = _this.elementList.splice(oldIndex, 1)[0];
            _this.elementList.splice(newIndex, 0, currRow);
          },
        });
      },
      // 移除单个模块
      removeModule(id) {
        if (this.elementSaving) return;

        this.$confirm('确认删除这个数据吗?删掉了就没有了哦').then(() => {
          this.elementSaving = true;
          this.$service
            .CmsElementDelete({
              elementIds: id,
            })
            .then((res) => {
              this.$message.success('删除成功');
              this.getElementList();
            })
            .finally(() => {
              this.elementSaving = false;
            });
        });
      },
    },
  };
</script>

<style lang="less" scoped>
  .module-detail {
    .element {
      padding: 10px;
      // border: 2px dashed #eee;
      background-color: #eee;
      border-radius: 5px;
      margin-bottom: 5px;
      position: relative;
      min-height: 50px;
      border-top: 30px solid grey;

      .element-body {
      }

      .element-cover {
        width: 150px;
      }

      .element-order {
        min-width: 50px;
      }

      .element-info {
        font-size: 14px;
        margin-left: 10px;
        width: 600px;
        word-break: break-all;
      }

      .btn-box {
        margin-left: auto;
        width: 200px;
      }
      .el-switch {
        width: 150px;
        flex: none;
      }
      &.offline {
        background: rgba(#e4e7ed, 0.2);
      }
    }
  }

  .data-edit {
    // display: flex;
    flex-direction: column;

    .module-icon {
      float: right;

      i {
        margin-left: 10px;
        font-size: 16px;

        &:hover {
          color: #409eff;
        }
      }
      & .is-active {
        color: #409eff;
      }
    }

    /deep/ .el-table th {
      background-color: #e5e5e5 !important;
    }

    .module-table-img {
      display: inline-block;
      width: 80px;
      height: 39px;
      vertical-align: middle;
      margin-right: 20px;
    }
  }

  .selected-element-box {
    display: flex;
    padding-left: 5px;
    .item {
      margin-right: 5px;
      cursor: pointer;
    }
  }
</style>
